/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LIUYANJIAO
 * Date: 2024-11-01
 * Time: 15:54
 */
public class polynomial {
    public static class Node{
        int coefficient;
        int index;
        Node next;

        public Node(int coefficient, int index) {
            this.coefficient = coefficient;
            this.index = index;
        }

        @Override
        public String toString() {
            return coefficient+"^"+index;
        }
    }
    Node head=null;
    //生成多项式

    public void add(Node node){
        if(head==null){
            head=node;
            return;
        }
        Node pcur=head;
        while(pcur.next!=null){
            pcur=pcur.next;
        }
        pcur.next=node;
    }
    //多项式相加
    public static int sumchild(polynomial p){
        int sum=0;
        Node pcur=p.head;
        while(pcur!=null){
            sum+=Math.pow(pcur.coefficient,pcur.index);
            pcur=pcur.next;
        }
        return sum;
    }
    public static int sum(polynomial p1, polynomial p2){
        return sumchild(p1)+sumchild(p2);
    }
    //输出多项式
    public static void print(polynomial p){
        Node node=p.head;
        while(node!=null){
            if(node.next!=null){
                System.out.print(node.toString()+"+");
            }else{
                System.out.print(node.toString()+"="+sumchild(p));
            }
            node=node.next;
        }
    }
    public static void main(String[] args) {
        polynomial p1=new polynomial();
        Node node=new Node(3,3);
        Node node1=new Node(4,4);
        Node node2=new Node(1,3);
        p1.add(node);
        p1.add(node1);
        p1.add(node2);
        polynomial p2=new polynomial();
        Node node3=new Node(8,3);
        Node node4=new Node(9,4);
        Node node5=new Node(7,3);
        p2.add(node3);
        p2.add(node4);
        p2.add(node5);
        int sum=sum(p1,p2);
        System.out.println("生成两个多项式：");
        print(p1);
        System.out.println();
        print(p2);
        System.out.println();
        System.out.println("两个多项式相加的和为："+sum);
    }
}
